package com.zqc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zqc.common.Const;
import com.zqc.common.R;
import com.zqc.entity.*;
import com.zqc.exception.CustomException;
import com.zqc.service.*;
import com.zqc.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    public OrdersService ordersService;

    @Autowired
    public ShoppingCartService shoppingCartService;

    @Autowired
    public AddressBookService addressBookService;

    @Autowired
    public UserService userService;

    @Autowired
    public OrderDetailService orderDetailService;

    @PostMapping("/submit")
    @Transactional
    public R<String> submit(@RequestBody Orders orders) {
        // 1 获取用户信息
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("用户登录异常");
        }
        // 2 查询购物车信息
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 3 查询地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("订单地址错误，不能下单");
        }

        // 订单id
        Long orderId = IdWorker.getId();

        // 计算订单金额 和 设置订单详情
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setImage(item.getImage());
            orderDetail.setName(item.getName());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setAmount(item.getAmount());

            // 计算订单总金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 4 设置order属性
        orders.setId(orderId);
        // 订单号
        orders.setNumber(String.valueOf(IdWorker.getId()));
        // 订单状态设置为待发货
        orders.setStatus(Const.DAIFAHUO);
        orders.setUserId(userId);
        orders.setUserName(user.getName());// 下单人
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());// 付款时间
        orders.setConsignee(addressBook.getConsignee());// 收货人
        orders.setPhone(addressBook.getPhone());
        orders.setAmount(new BigDecimal(amount.get()));// 总金额
        // 地址信息
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
        // 5 创建订单
        ordersService.save(orders);

        // 6 插入多条订单详情数据
        orderDetailService.saveBatch(orderDetails);

        // 7 删除购物车信息
        shoppingCartService.remove(queryWrapper);

        return R.success("下单成功");
    }

    /**
     * 后台订单分页查询
     *
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(int page, int pageSize, String number, String beginTime, String endTime) {

        // 创建Page
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        // 查询数据
        ordersService.page(ordersPage, new LambdaQueryWrapper<Orders>()
                .like(number != null, Orders::getNumber, number)
                .ge(beginTime != null, Orders::getOrderTime, beginTime)
                .le(endTime != null, Orders::getOrderTime, endTime));


        return R.success(ordersPage);
    }

    /**
     * 修改订单状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<Orders> updateStatus(@RequestBody Orders orders) {
        // 查询当前订单是否存在
        Orders orders1 = ordersService.getById(orders.getId());
        if (orders1 == null) {
            throw new CustomException("该订单不存在");
        }
        // 判断订单状态是否在修改状态的前一个状态
        if (orders1.getStatus() != orders.getStatus() - 1) {
            throw new CustomException("订单状态异常");
        }

        // 订单存在，修改订单状态为3，已派送
        orders1.setStatus(orders.getStatus());

        // 更新数据库
        ordersService.updateById(orders1);
        return R.success(orders1);
    }

    /**
     * 前台展示用户最新订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<Orders>> userPage(int page, int pageSize) {
        Long userId = BaseContext.getCurrentId();
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersService.page(ordersPage, new LambdaQueryWrapper<Orders>()
                .eq(userId != null, Orders::getUserId, userId)
                .orderByAsc(Orders::getOrderTime));

        return R.success(ordersPage);
    }

    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        // 先查询订单详情加入到购物车
        ordersService.again(orders);

        return R.success("再来一单");
    }

}
